package com.julis.activity.obu_function;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.Constant;
import com.android.scj.tc.TcAppFolw;
import com.baseutils.File_Z;
import com.baseutils.SpfUtils;
import com.baseutils.Write_Message;
import com.bean.TradeMessage;
import com.github.czy1121.view.RoundButton;
import com.julis.R;
import com.julis.db.Z_TradeInfoDao;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.thread.FalsePurchaseThread;
import com.thread.OffLineThread;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * obu零元消费
 */
public class OBU_Trade_Activity extends AppCompatActivity {

    @BindView(R.id.img_back)
    RelativeLayout imgBack;
    @BindView(R.id.textView22)
    TextView textView22;
    @BindView(R.id.et_phone)
    EditText etPhone;

    @BindView(R.id.bt_Start)
    RoundButton btStart;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    @BindView(R.id.tishi)
    TextView tishi;
    @BindView(R.id.tongji)
    TextView tongji;

    @BindView(R.id.tv_time)
    TextView tv_time;

    static String path, time2;
    boolean psamopen;
    Z_TradeInfoDao z_tradeInfoDao;
    List<String> ccList = new ArrayList<String>();
    List<String> ccList2 = new ArrayList<String>();
    ArrayAdapter<String> spinnerAdapter, spinnerAdapter2;
    @BindView(R.id.spinner_blood_pressure)
    Spinner spinnerBloodPressure;
    String name;
    @BindView(R.id.spinner_jiaoyi)
    Spinner spinnerBloodPressure2;
    int vaule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tradeinfo);
        ButterKnife.bind(this);
        z_tradeInfoDao = new Z_TradeInfoDao(this);
        psamopen = (boolean) SpfUtils.get(this, Constant.Check_Psam, true);
        OffLineThread setParam = new OffLineThread("A9_2", OBU_Trade_Activity.this);
        setParam.start();
        path = File_Z.createFile(OBU_Trade_Activity.this);
        ccList.add("交易成功");
        ccList.add("交易失败");
        ccList2.add("1");
        ccList2.add("2");
        ccList2.add("3");
        ccList2.add("4");
        ccList2.add("5");
        spinnerAdapter = new ArrayAdapter<String>(OBU_Trade_Activity.this,
                R.layout.item_select, ccList);
        spinnerAdapter.setDropDownViewResource(R.layout.item_drop);
        spinnerAdapter2 = new ArrayAdapter<String>(OBU_Trade_Activity.this,
                R.layout.item_select, ccList2);
        spinnerAdapter2.setDropDownViewResource(R.layout.item_drop);
        spinnerBloodPressure.setAdapter(spinnerAdapter);
        spinnerBloodPressure2.setAdapter(spinnerAdapter2);
        spinnerBloodPressure.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                name = ccList.get(pos);


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinnerBloodPressure2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                String VALUE = ccList2.get(pos);
                vaule = Integer.parseInt(VALUE);
                SpfUtils.put(OBU_Trade_Activity.this, "tradetime", vaule);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        int tradetime = (int) SpfUtils.get(OBU_Trade_Activity.this, "tradetime", 2);
        setSpinnerItemSelectedByValue(spinnerBloodPressure2, "" + tradetime);
    }

    String type = "";
    String tishimessage, tishimessageVALUE;
    FalsePurchaseThread purchase;
    TradeMessage tradeMessage;

    @SuppressLint("HandlerLeak")
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tradeMessage = (TradeMessage) msg.obj;
            String mac = tradeMessage.getMac();

            String Message = tradeMessage.getMessage();
            String Sn = tradeMessage.getSn();
            switch (msg.what) {
                case 1:
                    type = "成功";
                    tishimessage = "预设" + tradeMessage.getnTradeTotal() + "次，" + ",当前第" + tradeMessage.getnTradeCount() + "次交易" + " " + type + "，总计交易" + tradeMessage.getnTradeCount() + "次，当前交易成功" + tradeMessage.getnTradeSuccessNumber() + "次，失败" + tradeMessage.getnTradeFailNumber() + "次" + "当前mac:" + mac;
                    tishimessageVALUE = "预设" + tradeMessage.getnTradeTotal() + "次" + "\n" + "当前第" + tradeMessage.getnTradeCount() + "次交易" + "\n" + Message + "\n" + "总计交易" + tradeMessage.getnTradeCount() + "次" + "\n" + "当前交易成功" + tradeMessage.getnTradeSuccessNumber() + "次，" + "失败" + tradeMessage.getnTradeFailNumber() + "次" + "\n" + "当前mac:" + mac + "\n" + "当前SN:" + Sn;
                    z_tradeInfoDao.addTrade(Sn, mac, type, tradeMessage.getTime(), Message);
                    break;
                case 2:
                    type = "失败";
                    tishimessage = "预设" + tradeMessage.getnTradeTotal() + "次，" + ",当前第" + tradeMessage.getnTradeCount() + "次交易" + " " + type + "，总计交易" + tradeMessage.getnTradeCount() + "次，当前交易成功" + tradeMessage.getnTradeSuccessNumber() + "次，失败" + tradeMessage.getnTradeFailNumber() + "次" + "当前mac:" + mac;
                    tishimessageVALUE = "预设" + tradeMessage.getnTradeTotal() + "次" + "\n" + "当前第" + tradeMessage.getnTradeCount() + "次交易" + "\n" + Message + "\n" + "总计交易" + tradeMessage.getnTradeCount() + "次" + "\n" + "当前交易成功" + tradeMessage.getnTradeSuccessNumber() + "次，" + "失败" + tradeMessage.getnTradeFailNumber() + "次" + "\n" + "当前mac:" + mac + "\n" + "当前SN:";
                    z_tradeInfoDao.addTrade("", mac, type, tradeMessage.getTime(), Message);
                    break;
                case 3://测试完成
                    tishimessageVALUE = "测试结束" + "\n" + "预设" + tradeMessage.getnTradeTotal() + "次" + "\n" + "总计交易" + tradeMessage.getnTradeCount() + "次" + "\n" + "当前交易成功" + tradeMessage.getnTradeSuccessNumber() + "次，" + "失败" + tradeMessage.getnTradeFailNumber() + "次" + "\n";
                    tishimessage = tishimessageVALUE;
                    break;
                case 4://测试中断


                    tishimessageVALUE = "测试中断" + "\n" + "预设" + tradeMessage.getnTradeTotal() + "次" + "\n" + "总计交易" + tradeMessage.getnTradeCount() + "次" + "\n" + "当前交易成功" + tradeMessage.getnTradeSuccessNumber() + "次，" + "失败" + tradeMessage.getnTradeFailNumber() + "次" + "\n";
                    tishimessage = tishimessageVALUE;
                    break;
                default:
                    return;
            }

            Write_Message.write(path, OBU_Trade_Activity.this, tishimessage, time2);
            tongji.setText(tishimessageVALUE);
            if (msg.what < 3)
                tv_time.setText("本次交易时长：" + tradeMessage.getTime());
            else//测试结束
            {
                Toast.makeText(OBU_Trade_Activity.this, "测试交易完成!", Toast.LENGTH_SHORT).show();
                etPhone.setEnabled(true);
                btStart.setText("开始交易");
                tishi.setVisibility(View.VISIBLE);
                tingzhi = false;
                spinnerBloodPressure.setEnabled(true);
                spinnerBloodPressure2.setEnabled(true);
            }


        }
    };

    int tradeTotal = 1;
    boolean tingzhi = false;

    @OnClick({R.id.img_back, R.id.bt_Start, R.id.bt_Shangchan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                tingzhi = true;
                stop();
                finish();
                break;
            case R.id.bt_Shangchan:

                startActivity(new Intent(this, TradeRecord_List_Activity.class));
                break;

            case R.id.bt_Start:
                //成功
                TcAppFolw.DATATrada = "00";

                if (btStart.getText().toString().equals("开始交易")) {
                    spinnerBloodPressure.setEnabled(false);
                    spinnerBloodPressure2.setEnabled(false);
                    time2 = File_Z.GetNowDate2();
                    tv_time.setText("提示：");
                    btStart.setText("停止交易");
                    startobu();
                } else {
                    spinnerBloodPressure.setEnabled(true);
                    spinnerBloodPressure2.setEnabled(true);
                    tingzhi = true;
                    stop();

                }


                break;
        }
    }

    public void startobu() {

        tongji.setText("开始交易");
        String sV = etPhone.getText().toString();

        if (TextUtils.isEmpty(sV)) {
            tradeTotal = 1;
            Toast.makeText(this, "默认测试交易次数为1次!", Toast.LENGTH_SHORT).show();
        } else {
            int i = Integer.parseInt(sV);
            if (i < 1) {
                Toast.makeText(this, "不能输入小于1的次数!", Toast.LENGTH_SHORT).show();
            } else {
                tradeTotal = i;
            }
        }
        Write_Message.write(path, OBU_Trade_Activity.this, "预设" + tradeTotal + "次,开始交易", time2);
        Log.e("time2", " " + time2);
        etPhone.setEnabled(false);
        tishi.setVisibility(View.GONE);
        tongji.setVisibility(View.VISIBLE);
        //   Write_Message.write(path ,OBU_Trade_Activity.this,"第" + 1 + "次交易"+" "+"开始！",time2);
        start();
    }


    KProgressHUD dialog1;

    public void showdialog1() {
        dialog1 = KProgressHUD.create(OBU_Trade_Activity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在测试交易中")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)

                .show();
    }

    public void start() {
        int tradetime = (int) SpfUtils.get(OBU_Trade_Activity.this, "tradetime", 2);
        purchase = new FalsePurchaseThread(handler1, OBU_Trade_Activity.this, psamopen, tradeTotal, tradetime * 1000);
        purchase.start();
    }

    public void stop() {
        if (purchase!=null) {
            purchase.setRun(false);
        } else {

        }


    }

    /**
     * 根据值, 设置spinner默认选中:
     *
     * @param spinner
     * @param value
     */
    public static void setSpinnerItemSelectedByValue(Spinner spinner, String value) {

        SpinnerAdapter apsAdapter = spinner.getAdapter(); //得到SpinnerAdapter对象
        int k = apsAdapter.getCount();
        for (int i = 0; i < k; i++) {
            if (value.equals(apsAdapter.getItem(i).toString())) {
                spinner.setSelection(i, true);// 默认选中项
                break;
            }
        }
    }


}
